/*  
 *  Copyright 2006 Paul Jack.
 *
 *  This file is part of the Dex compiler suite. 
 *  
 *  Dex is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *  
 *  Dex is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 *  Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */
package dex.compiler.checker;


import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import dex.compiler.checker.type.Type;


/**
 * Scope for local variables.
 */
class Scope {


	/** 
	 * The stack of scopes.
	 */
	private List<Map<String,Type>> locals;
	
	
	/**
	 * Constructs a new empty scope.
	 */
	public Scope() {
		this.locals = new LinkedList<Map<String,Type>>();
	}
	
	
	/**
	 * Adds a local variable to the current scope.
	 * 
	 * @param name  the name of the variable to add
	 * @param type  the type of the variable to add
	 */
	public void addLocalVariable(String name, Type type) {
		if (name == null) {
			throw new IllegalArgumentException("name cannot be null");
		}
		if (type == null) {
			throw new IllegalArgumentException("name cannot be null");
		}
		Type t = getType(name);
		if (t != null) {
			throw new IllegalArgumentException(name + " already exists.");
		}
		
		Map<String,Type> last = locals.get(0);
		last.put(name, type);
	}


	/**
	 * Returns the type of the given variable.  Or, null if the variable
	 * is not in this scope.
	 * 
	 * @param variable  the variable to check
	 * @return  the type of that variable, or null if there isn't one
	 */
	public Type getType(String variable) {
		for (Map<String,Type> block: locals) {
			Type r = block.get(variable);
			if (r != null) {
				return r;
			}
		}
		return null;
	}
	
	
	public void enter() {
		locals.add(0, new HashMap<String,Type>());
	}
	
	
	public void exit() {
		locals.remove(0);
	}
}
